package cn.jiemusic.service.impl;

import cn.jiemusic.domain.po.Music;
import cn.jiemusic.domain.po.UserLike;
import cn.jiemusic.domain.vo.MusicVo;
import cn.jiemusic.mapper.MusicMapper;
import cn.jiemusic.service.MusicService;
import cn.jiemusic.service.UserLikeService;
import cn.jiemusic.utils.BeanCopyUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MusicServiceImpl extends ServiceImpl<MusicMapper, Music> implements MusicService {
    @Autowired
    private UserLikeService userLikeService;

    @Override
    public List<MusicVo> getRandomList(String uid, int n) {
        UserLike userLike = userLikeService.getById(uid);

        QueryWrapper<Music> queryWrapper = new QueryWrapper<>();
        queryWrapper.last("ORDER BY RAND() LIMIT " + n);

        List<Music> musics = list(queryWrapper);

        // 将用户喜欢的歌曲 ID 列表转换为 Set
        Set<Long> likeSongSet = new HashSet<>(userLike.getLikeSong());


        // 将 Music 转换为 MusicVo，并设置 isLove 属性
        // 根据 Set 判断是否喜欢
        return musics.stream()
                .map(music -> {
                    MusicVo musicVo = new MusicVo();
                    BeanUtils.copyProperties(music, musicVo);
                    musicVo.setIsLove(likeSongSet.contains(music.getId())); // 根据 Set 判断是否喜欢
                    return musicVo;
                })
                .toList();
    }

    @Override
    public List<MusicVo> getLikeList(String uid) {
        UserLike userLike = userLikeService.getById(uid);

        // 根据喜欢的歌曲 ID 列表获取 Music 对象并映射为 MusicVo
        List<MusicVo> vos = new ArrayList<>(userLike.getLikeSong().stream()
                .map(this::getById) // 根据 ID 获取 Music 对象
                .map(music -> {
                    MusicVo vo = BeanCopyUtils.copyBean(music, MusicVo.class); // 复制属性
                    vo.setIsLove(true); // 设置喜欢状态
                    return vo;
                })
                .toList());

        // 反转结果列表
        Collections.reverse(vos);
        // 将 likeSong 转为流
        return vos;
    }

    @Override
    public MusicVo getMvoById(String mid, String uid) {
        // 获取 Music 对象
        Music music = getById(mid);

        // 复制 Music 到 MusicVo
        MusicVo musicVo = BeanCopyUtils.copyBean(music, MusicVo.class);

        // 获取用户喜欢的歌曲列表，并设置 isLove 属性
        UserLike userLike = userLikeService.getById(uid);
        musicVo.setIsLove(userLike.getLikeSong().contains(musicVo.getId()));

        return musicVo;
    }
}
